import BatchOperation, { OperationType } from '@/components/BatchOperation';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import {
  addAccount,
  batchStatus,
  enableAccount,
  freezeAccount,
  getAccountList,
  getDeptList,
  getRoleList,
  updateAccount,
  updateAccountRoleBatch
} from '@/services/permissions/api';
import { OptType } from '@/utils/constants';
import { MsgType, isNull, showMsg } from '@/utils/utils';
import { PlusOutlined } from '@ant-design/icons';
import ProForm, { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Popconfirm, Tooltip } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import BatchAdd from './BatchAdd';
import OptForm from './OptForm';
import SubAdd from './SubAdd';

const AccountList = () => {

  // 角色列表
  const [roleList, setRoleList] = useState<{ label: string; value: string; }[]>([]);
  // 部门列表
  const [deptList, setDeptList] = useState<PERMISSIONSAPI.DeptInfo[]>([]);
  // 批量操作类型
  const [selectedBAType, setSelectedBAType] = useState<BatchActionType>('N');
  // 列表选中的行数据
  const [selectedRows, setSelectedRows] = useState<PERMISSIONSAPI.AccountListItem[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const actionRef = useRef<ActionType>();
  // 编辑弹窗显示状态
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  // 当前编辑行需要的数据
  const [editRowData, setEditRowData] = useState<PERMISSIONSAPI.AccountListItem>();
  const [superAdminInfo, setSuperAdminInfo] = useState<any>(null);
  // 编辑类型：新增/修改
  const [editType, setEditType] = useState<string>(OptType.ADD);
  // 高亮当前点击的行
  const [clickRow, setClickRow] = useState('');

  // 新增弹窗
  const [showAddModal, setShowAddModal] = useState(false);
  // 批量修改角色窗口显示
  const [roleBatchUpdateVisible, setRoleBatchUpdateVisible] = useState<boolean>(false);

  const { initialState } = useModel('@@initialState');
  const oper_id = initialState?.currentUser?.oper_id || '';
  const dept_level = initialState?.currentUser?.dept_level;

  const columns: ProColumns<PERMISSIONSAPI.AccountListItem>[] = [
    {
      title: '业务科室',
      dataIndex: 'dept_code',
      hideInTable: true,
      valueType: 'select',
      hideInSearch: dept_level === '2',
      colSize: 3,
      formItemProps: { labelCol: { flex: '0 0 80px' } },
      initialValue: initialState?.currentUser?.identity_type !== 'A' ? initialState?.currentUser?.dept_code : null,
      fieldProps: {
        options: deptList.map(item => {
          return {
            label: <Tooltip title={`${item.dept_code}-${item.dept_name}`}>{item.dept_code}-{item.dept_name}</Tooltip>,
            value: item.dept_code,
            data: item,
            py: `${item.dept_code}-${item.dept_name}`
          }
        }),
        optionFilterProp: 'py',
        showSearch: true,
        filterOption: (input: any, option: any) => {
          // console.log('(option.py).toLowerCase()', (option.py || ''), input);
          return ((option?.py || '').toLowerCase()).includes(input)
        },
        disabled: initialState?.currentUser?.identity_type !== 'A',
      }
    },
    {
      title: '所属业务科室',
      dataIndex: 'dept_name',
      hideInSearch: true,
      hideInTable: dept_level === '2'
    },
    {
      title: '员工工号',
      dataIndex: 'staff_code',
      hideInTable: dept_level === '2',
      hideInSearch: dept_level === '2',
      colSize: 2.5
    },
    {
      title: '员工登录账号',
      dataIndex: 'mobile',
      hideInSearch: dept_level === '1',
      hideInTable: dept_level === '1',
      formItemProps: {
        labelCol: { flex: '0 0 80px' }
      },
      colSize: 2.5
    },
    {
      title: '员工姓名',
      dataIndex: 'oper_name',
      colSize: 2.5
    },
    {
      title: '是否超管',
      dataIndex: 'identity_type',
      search: false,
      render: (value) => {
        return value === 'S' ? '是' : '否';
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role_name',
      search: false
    },
    {
      title: '账号状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        N: '已启用',
        S: '已停用',
        W: '待分配'
      },
      colSize: 2.5
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (_, record) => [
        record.oper_id !== oper_id &&
        <Popconfirm key="status"
          title={`是否${record.status === 'N' ? '停用' : '启用'}该账户`}
          onConfirm={() => onStateChange(record, () => { actionRef.current?.reload(); })}
        >
          <a>{record.status === 'N' ? '停用' : '启用'}</a>
        </Popconfirm>
        ,
        <a key="edit"
          onClick={() => {
            setEditRowData(record);
            setEditType(OptType.EDIT);
            if (dept_level === '1') {
              setEditModalVisible(true);
            } else {
              setShowAddModal(true);
            }
          }}>编辑</a>
      ]
    }
  ];

  useEffect(() => {
    getDeptList({}).then(res => {
      setDeptList(res || [])
    }).catch(error => {
      showMsg(error?.data?.errmsg)
    })
  }, [])

  /**
   * 根据部门编码查询角色列表
   * @param dept_code
   * @param callback
   */
  const fetchRole = (dept_code: string, callback?: () => void) => {
    getRoleList({ current: 1, pageSize: 9999, dept_code }).then((res: PERMISSIONSAPI.RoleList) => {
      const data = res?.record_list?.map((item) => ({
        label: item.role_name as string,
        value: item.role_id as string,
        dept_code: item.dept_code as string
      }));
      setRoleList(data || []);
      callback?.();
    }).catch(err => {
      showMsg(err?.data?.errmsg);
    })
  }

  /**
     * 院内账号账号编辑
     * @param fields
     * @returns
     */
  const hospitalAccountEdit = async (fields: PERMISSIONSAPI.AccountListItem) => {
    try {
      if (editType === OptType.ADD) {
        await addAccount({ ...fields });
      } else {
        await updateAccount({ ...fields });
      }
      showMsg('已保存', MsgType.SUCCESS);
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
      return false;
    }
  };

  /**
   * 修改账号状态
   * @param info
   * @returns
   */
  const onStateChange = async (info: PERMISSIONSAPI.AccountListItem, callback: () => void) => {
    if (!info) return;
    try {
      if (info.status === 'N') {
        await freezeAccount([info.oper_id as string]);
        showMsg('账号已停用', MsgType.SUCCESS);
      } else {
        await enableAccount([info.oper_id as string]);
        showMsg('账号已启用', MsgType.SUCCESS);
      }
      callback?.();
    } catch (error: any) {
      showMsg(error?.data?.errmsg);
    }
  };

  /**
   * 批量修改账号状态
   */
  const onBatchStateChange = async ({ label, value }: OperationType<BatchActionType>) => {
    console.info(selectedRowKeys, label, value);
    await batchStatus({ oper_id_list: selectedRowKeys, status: value }).then(res => {
      showMsg(`已批量修改为“${label}”`, 'success');
      setSelectedRowKeys([]);
      actionRef.current?.clearSelected?.();
      actionRef?.current?.reload();
    }).catch((error) => {
      showMsg(error?.data?.errmsg);
    });
  }

  /**
   * 批量修改角色
   */
  const onBatchRoleChange = async () => {
    const deptLst = selectedRows.map((item) => item.dept_code);
    const result = Array.from(new Set(deptLst));
    if (result.length > 1) {
      showMsg('批量修改角色操作需保证选定人员均归属同一业务科室。');
      return;
    }
    fetchRole(result[0] || '', () => {
      setRoleBatchUpdateVisible(true);
    });
  }

  return (
    <PageContainer extra={<BreadcrumbDept />} breadcrumb={{}}>
      <ProTable<PERMISSIONSAPI.AccountListItem, COMMON.PageParams & PERMISSIONSAPI.AccountListItem>
        actionRef={actionRef}
        rowKey="oper_id"
        columns={columns}
        options={false}
        onRow={record => ({ onClick: () => setClickRow(record.oper_id as string) })}
        rowClassName={(record) => record.oper_id === clickRow ? 'tableRowClick' : ''}
        pagination={{ showQuickJumper: true }}
        bordered
        search={{
          span: 2,
          labelWidth: 70,
          collapsed: false,
          collapseRender: false,
          optionRender: (searchConfig, formProps, [, searchBtn]) => [searchBtn]
        }}
        request={async (params) => {
          console.info(params);
          try {
            const data: PERMISSIONSAPI.AccountList = await getAccountList(params);
            const superAdmin = data.record_list?.find((item) => item.identity_type === 'S');
            setSuperAdminInfo(superAdmin);
            return { data: data.record_list, success: true, total: data.sum_record_num };
          } catch (error: any) {
            showMsg(error?.data?.errmsg);
            return { data: [], success: true, total: 0 };
          }
        }}
        rowSelection={{
          columnWidth: 30,
          onChange: (keys, rows) => {
            setSelectedRowKeys(keys);
            setSelectedRows(rows);
          },
          hideSelectAll: selectedBAType === 'U',
          getCheckboxProps: (record) => {
            return {
              disabled:
                selectedBAType !== 'U'
                  ? record.oper_id === oper_id || selectedBAType === record.status
                  : selectedRows.length > 0 && selectedRows[0].dept_code !== record.dept_code
            };
          }
        }}
        toolbar={{
          menu: {
            items: [
              {
                key: 'add',
                label: <Button onClick={() => setShowAddModal(true)} icon={<PlusOutlined />} type="primary">新增</Button>
              },
              {
                key: 'batch',
                label: <BatchOperation<BatchActionType>
                  tips='批量操作需保证选定人员均归属同一业务科室。'
                  onChange={({ value }) => {
                    actionRef.current?.clearSelected?.();
                    setSelectedRowKeys([]);
                    setSelectedBAType(value);
                  }}
                  disable={isNull(selectedRowKeys)}
                  options={[
                    { value: 'N', label: '启用', confirmText: '将选中记录修改为“启用”状态，是否确认？', onOk: onBatchStateChange },
                    { value: 'S', label: '停用', confirmText: '将选中记录修改为“停用”状态，是否确认？', onOk: onBatchStateChange },
                    { value: 'U', label: '修改角色', confirm: false, onOk: () => onBatchRoleChange() }
                  ]}
                />
              }
            ]
          }
        }}
      />
      {
        // 批量修改角色弹窗
        roleBatchUpdateVisible && (
          <ModalForm
            title="批量修改角色"
            width="40%"
            visible
            modalProps={{
              maskClosable: false,
            }}
            layout="horizontal"
            onVisibleChange={setRoleBatchUpdateVisible}
            onFinish={async (value) => {
              try {
                await updateAccountRoleBatch({
                  oper_id_list: selectedRowKeys,
                  ...value,
                });
                showMsg('已批量修改', MsgType.SUCCESS);
                window.location.reload();
                setRoleBatchUpdateVisible(false);
                if (actionRef.current) {
                  // @ts-ignore
                  actionRef.current.clearSelected();
                  actionRef.current.reload();
                }
              } catch (error: any) {
                showMsg(error?.data?.errmsg);
              }
            }}
            submitter={{
              searchConfig: {
                resetText: '关闭',
                submitText: '保存',
              },
            }}
          >
            <ProForm.Group>
              <ProFormText label="所属业务科室" width="md" name="dept_name" initialValue={selectedRows[0].dept_name} readonly />
              <ProFormSelect
                rules={[{ required: true }]}
                width="md"
                options={roleList}
                placeholder="请选择角色"
                name="role_id"
                label="角色分配"
                labelCol={{ flex: '86px' }}
                wrapperCol={{ span: 14, flex: '250px' }}
              />
            </ProForm.Group>
          </ModalForm>
        )
      }
      {
        // 选中行修改弹窗
        dept_level === '1' && editModalVisible && (
          <OptForm
            handleModalVisible={setEditModalVisible}
            record={editRowData}
            optType={editType}
            handleAdd={hospitalAccountEdit}
            roleList={roleList}
            superAdmin={superAdminInfo}
          />
        )
      }
      {
        // 批量新增弹窗
        dept_level === '1' && showAddModal &&
        <BatchAdd
          deptList={deptList}
          handleModalVisible={(flag: any) => {
            setShowAddModal(flag);
            if (flag) {
              actionRef.current?.reload();
            }
          }}
        />
      }
      {
        dept_level === '2' && showAddModal &&
        <SubAdd
          editData={editRowData}
          handleModalVisible={visible => {
            setShowAddModal(visible);
            if (!visible)
              setEditRowData(undefined);
          }}
          finishCallback={() => {
            setShowAddModal(false);
            actionRef.current?.reload();
          }} />
      }
    </PageContainer>
  );
};

export default AccountList;

type BatchActionType = 'N' | 'S' | 'U';
